import React, { Component } from 'react'
import { Link } from 'react-router-dom';
import { Table, Row, Col, Upload, Select, Button, Modal,Form ,message, Icon,Breadcrumb,Spin } from 'antd';
import api from '../../../api/api';
import { connectRouter } from '../../../mixins/router';
import './BuyGroupInsurance.less'
import history from '../../../history'
let FormItem = Form.Item




class BuyGroupInsurance extends Component {
    constructor(props) {
        super(props);
        this.state = {
          groupInsuranceId:'',
          uploadResult:{},
          groupInsuranceProducts:[],  // 团险产品
          currentProduct:{},
          verificationModal:false,
          fileList:[],
          productValue:[],
          groupInsuranceDetail:{},
          loading:false
        }
    }
    async componentDidMount(){
      // 查询团险保险产品
      let groupInsuranceProducts = await api.getInsuranceProducts() || []
      // return false
      this.setState({
        groupInsuranceProducts
      })
      // 点击列表页的提交按钮，如果是从列表传过来的，获取传过来的保险名称
      let router = this.props.router
      let groupInsuranceId = router.query.id
      let productId = router.query.productId
      let target = groupInsuranceProducts.find(item=>{
        return item.productId === +productId
      })

      if(target){
        // 获取订单详情
        let groupInsuranceDetail = await api.getGroupInsuranceDetail(groupInsuranceId)
        this.setState({
          productValue:[String(target.productId)],
          currentProduct:target,
          groupInsuranceDetail,
          groupInsuranceId
        })

      }
    }
    submitToService = () => {
      this.setState({
        loading:true
      })
      let { productValue,fileList } = this.state
      let form = new FormData()
      form.append('file',fileList[0].originFileObj)
      // fetch(`/_api/groupInsurance?productId=${productValue[0]}`,{
      fetch(`/_api/groupInsurance?productId=${productValue[0]}`,{
        body:form,
        method:'POST'
      }).then(res=>{
        return res.json()
      }).then(data=>{
        this.setState({
          loading:false
        })
        if(data.code ===0 ){
          // 提交的数据有问题
          if(data.data && data.data.length>0){
            this.setState({
              uploadResult:{
                count:data.data.length,
                errors:data.data
              },
              verificationModal:true
            })
          }else{
            // 提交正确，且没问题,清空上传内容，返回列表
            this.goBack()
          }
        }else{
          this.setState({
            uploadResult:{}
          })
          Modal.confirm({
            title:'提交确认',
            content:data.message || '提交数据至服务器报错，请稍后重试',
            okText:'确定',
          })
          return
        }
      }).catch(()=>{
        this.setState({
          loading:false
        })
      })
    }

    reSubmitToService = () => {
      this.setState({
        loading:true
      })
      // fetch(`/_api/groupInsurance?productId=${productValue[0]}`,{
      fetch(`/_api/groupInsurance?groupOrderId=${this.state.groupInsuranceId}`,{
        method:'POST'
      }).then(res=>{
        return res.json()
      }).then(data=>{
        this.setState({
          loading:false
        })
        if(data.code ===0 ){
          // 提交的数据有问题
          if(data.data && data.data.length>0){
            this.setState({
              uploadResult:{
                count:data.data.length,
                errors:data.data
              },
              verificationModal:true
            })
          }else{
            // 提交正确，且没问题,清空上传内容，返回列表
            this.goBack()
          }
        }else{
          this.setState({
            uploadResult:{}
          })
          Modal.confirm({
            title:'提交确认',
            content:data.message || '提交数据至服务器报错，请稍后重试',
            okText:'确定',
          })
          return
        }
      }).catch(()=>{
        this.setState({
          loading:false
        })
      })
    }

    // 提交清单
    submit =()=>{
      let self = this
      let { productValue, fileList , uploadResult,groupInsuranceId} = this.state
      // 如果groupInsuranceId存在，则是编辑，用户时从列表页点击提交过来的，不需要再做校验
      if(groupInsuranceId){
        this.reSubmitToService()
      }else{
        if(productValue.length === 0){
          Modal.confirm({
            title:'提交确认',
            content:'投保产品不能为空，请选择投保产品',
            okText:'确定',
          })
          return
        }
        if(fileList.length === 0 ){
          Modal.confirm({
            title:'提交确认',
            content:'投保清单不能为空，请导入投保清单',
            okText:'确定',
          })
          return
        }
        if(uploadResult.errors && uploadResult.errors.length > 0){
          Modal.confirm({
            title:'提交确认',
            content:'投保清单校验不通过，请重新导入！',
            okText:'确定',
          })
          return
        }

        Modal.confirm({
          title:'提交确认',
          content:'操作后不可回退，是否提交？',
          okText:'确定',
          cancelText:'取消',
          onOk() {
            self.submitToService()
          },
          onCancel() {
            this.setState({
              loading:false
            })
          },
        })
      }



    }
    // 取消
    goBack =()=>{
      this.cancel()
      if (this.props.router.query.r && this.props.router.query.r.indexOf('/GroupOrderInsurance') === 0) {
        history.push(this.props.router.query.r);
      } else {
        history.push('/GroupOrderInsurance');
      }
    }

    cancel =()=>{
      this.setState({
        currentProduct:{},
        fileList:[],
        productValue:[],
        uploadResult:{}
      })
    }
    // 点击校验确定按钮
    verificationOk = ()=>{
      // 点击校验确定按钮
      this.setState({
        verificationModal:false
      })
    }
    verificationCancel=()=>{
      this.setState({
        verificationModal:false
      })
    }
    // 获取投保主体名称
    getInsurerTypeName=(val)=>{
      let insurer ={
        1: '万户',
        2: '爱尔公益基金会'
      }
      return insurer[val] || ''
    }
    productSelectChange=(value,a)=>{
      console.log('value:',value)
      console.log('a:',a)
      let initgroupInsuranceProducts = JSON.parse(JSON.stringify(this.state.groupInsuranceProducts))
      let target = initgroupInsuranceProducts.find(item=>{ return item.productId === +value})
      if(target){
        this.setState({
          currentProduct:target,
          productValue:[value]
        })
      }
    }
    beforeGroupInsuranceFileUpload=()=>{
      console.log('beforeGroupInsuranceFileUpload')
      if(this.state.productValue.length ===0 ){
        message.error('请先选择投保产品')
        this.setState({
          fileList:[]
        })
        return false
      }
    }
    removeFile =()=>{
      this.setState({
        fileList:[],
        uploadResult:{}
      })
    }
    groupInsuranceFileUpload=({file})=>{
      if(this.state.productValue.length ===0 ){
        return false
      }
      this.setState({
        fileList:[file]
      })
      let response = file.response
      if(response){
        if(response.code === 0){
          this.setState({
            uploadResult: response.data,
          })
          if(response.data.errors && response.data.errors.length > 0){
            this.setState({
              verificationModal: true
            })
          }
        }else{
          this.setState({
            fileList:[],
            uploadResult:{}
          })
          Modal.confirm({
            title:'上传提示',
            content:response.message || '上传文件失败, 请重新上传' ,
            okText:'确定',
            cancelText:'取消',
          })
        }
      }
    }
    goServiceDetail = (rowData)=>{

      window.open(`/patientInsuranceDetail/${rowData.id}?r=${encodeURIComponent(this.props.router.fullPath)}`,'_blank');
    }

    get backToIndex() {
      if (this.props.router.query.r && this.props.router.query.r.indexOf('/GroupOrderInsurance') === 0) {
        return this.props.router.query.r;
      } else {
        return '/GroupOrderInsurance';
      }
    }
    downloadList = ()=>{
      window.open(`/_api/oss/download?objectName=${this.state.groupInsuranceDetail.originObjectName}`)
    }
    formatObjectName = (objectName)=>{
      if(objectName){
        let index = objectName.indexOf('/')
        return objectName.slice(index+1)
      }
    }
    render(){
      let { groupInsuranceProducts ,currentProduct, verificationModal, uploadResult,fileList ,productValue,groupInsuranceDetail,groupInsuranceId, loading} = this.state
      const apiUrl = `_api/groupInsurance/excel/validate?productId=${productValue[0]}`;

      return (
        <div className="buyGroupInsurance">
          <Breadcrumb className="breadcrumb-box">
            <Breadcrumb.Item>
              <Link to={this.backToIndex}>团险订单管理</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>上传投保清单</Breadcrumb.Item>
          </Breadcrumb>


          <div className="main">
          {
            loading ? (
              <div className="loading-wrap">
                <Spin />
              </div>
            ) : ''
          }

            <div className="pro-info">
              <Row gutter={16}>
                <Col className="gutter-row gutter-row-pro" span={8}>
                  <div className="pro-label"><span style={{color:'red',marginRight:'5px'}}>*</span>投保产品：</div>
                  <Select placeholder="请选择投保产品" showSearch onChange={this.productSelectChange} value={productValue} disabled={groupInsuranceId !==''}
                    filterOption={(input,option)=>{
                      return option.props.children.props.title.indexOf(input) > -1
                    }}
                  >
                    {
                      groupInsuranceProducts.map((item)=>{
                        return <Select.Option key={item.productId} value={String(item.productId)}><span title={item.productName + ' ' +item.productCode}>{item.productName + ' ' +item.productCode}</span></Select.Option>
                      })
                    }
                  </Select>
                </Col>
                <Col className="gutter-row" span={8}>
                  <div className="gutter-box">
                    投保主体：{this.getInsurerTypeName(currentProduct.insurerType)}
                  </div>
                </Col>
                <Col className="gutter-row" span={8}>
                  <div className="gutter-box">
                    承保公司：{currentProduct.insuranceCompany}
                  </div>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col className="gutter-row" span={8}>
                  <div className="gutter-box">
                    投保方案代码：{currentProduct.insuranceSuitCode}
                  </div>
                </Col>
                <Col className="gutter-row" span={16}>
                  <div className="gutter-box">
                    备注：{currentProduct.note}
                  </div>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col className="gutter-row" span={8}>
                  <div className="gutter-box">
                    保险期限：1年
                  </div>
                </Col>
                <Col className="gutter-row" span={8}>
                  <div className="gutter-box">
                    缴费频次：月缴
                  </div>
                </Col>
                <Col className="gutter-row" span={8}>
                  <div className="gutter-box">
                    缴费期数：1/12
                  </div>
                </Col>
              </Row>
            </div>
            <div className="import">
              <Upload
                name="file"
                beforeUpload={this.beforeGroupInsuranceFileUpload}
                onChange={this.groupInsuranceFileUpload}
                action={ apiUrl }
                fileList={fileList}
                onRemove={this.removeFile}
                disabled={groupInsuranceId !==''}
                >
                <Button>
                  <Icon type="upload" /> 导入投保清单
                </Button>
              </Upload>
              <div className="import-red" style={{display:'flex',alignItems:'center'}}><Icon type="exclamation" style={{color:'#F59A23',fontSize:'20px'}}/>如被保人发生变化，请重新导入清单</div>
            </div>
              {
                Object.keys(uploadResult).length ? (
                  <div className="import-tip">
                    被保人数：{uploadResult.count}人
                  </div>
                ) : ''
              }
            {
              groupInsuranceId!=='' ? (
                <div>
                  <div className="goi-listfile" >
                    承保清单：<span className="goi-list-name" onClick={() => {this.downloadList(groupInsuranceDetail.originObjectName)}}>{ this.formatObjectName(groupInsuranceDetail.originObjectName)}</span>
                  </div>
                  <div className="import-tip">
                    被保人数：{groupInsuranceDetail.count}人
                  </div>
                </div>
              ) : ''
            }
            <div className="sub-btnW">
              <Button onClick={this.goBack} type="primary">返回</Button>
              <Button onClick={this.submit} type="primary">提交</Button>
            </div>

            {/* 弹窗 */}
            <Modal
              title="导入校验"
              visible={verificationModal}
              wrapClassName="vertical-center-modal"
              onCancel={this.verificationCancel}
              width="800px"
              footer={[
                <Button key="submit" type="primary" size="large" onClick={this.verificationOk}>
                  确定
                </Button>,
              ]}
            >
              {/* <div className="vertical-center-modal-bgi-title">被保人服务产品与投保产品不一致，请修改后重新导入！</div> */}
              <div className="vertical-center-modal-bgi-tip">以下会员数据校验不通过：</div>
              <Table dataSource={uploadResult.errors}  pagination={false} bordered>
                <Table.Column
                  dataIndex="orderNo"
                  title="服务订单号"
                  key="orderNo"
                  onCellClick={(rowData) => this.goServiceDetail(rowData)}
                  render={(text)=>{
                    return <span className="clickable">{text}</span>
                  }}
                />
                <Table.Column
                  title="服务包名称"
                  dataIndex="packageName"
                  key="packageName"
                />
                <Table.Column
                  title="被保人名称"
                  dataIndex="insuredName"
                  key="insuredName"
                />
                <Table.Column
                  title="被保人身份证号"
                  dataIndex="insuredIdCard"
                  key="insuredIdCard"
                />
                <Table.Column
                  title="校验结果"
                  dataIndex="message"
                  key="message"
                />
              </Table>
            </Modal>

          </div>
        </div>
      )
    }
}

const WrappedBuyGroupInsurance = Form.create()(BuyGroupInsurance);
export default connectRouter(WrappedBuyGroupInsurance);
